package com.ifsaid.im.service.impl;

import com.ifsaid.im.bo.LoginUser;
import com.ifsaid.im.common.service.impl.BaseServiceImpl;
import com.ifsaid.im.entity.FriendEntity;
import com.ifsaid.im.entity.UserEntity;
import com.ifsaid.im.exception.UserException;
import com.ifsaid.im.mapper.UserMapper;
import com.ifsaid.im.service.IEasemobImService;
import com.ifsaid.im.service.IFriendService;
import com.ifsaid.im.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.Set;

/**
 * @description: 用户 service 层 实现类
 * @author: Wang Chen Chen<932560435@qq.com>
 * @date: 2019/11/4 14:01
 */

@Slf4j
@Service
public class UserServiceImpl extends BaseServiceImpl<Integer, UserEntity, UserMapper> implements IUserService {

    @Autowired
    private PasswordEncoder encoder;

    @Autowired
    private IEasemobImService easemobImService;

    @Autowired
    private IFriendService friendService;

    @Override
    public UserEntity findUserByUsername(String username) {
        return baseMapper.findUserByUsername(username);
    }

    @Override
    public UserEntity registered(UserEntity entity) throws UserException {
        String encode = encoder.encode(entity.getPassword());
        entity.setPassword(encode);
        entity.setCreateTime(LocalDateTime.now());
        entity.setUpdateTime(LocalDateTime.now());
        // 先保存到数据库
        Integer save = save(entity);
        // 再将用户名和密码注册到环信
        easemobImService.registered(entity);
        return entity;
    }

    @Override
    public LoginUser login(String username, String password) throws UserException {
        UserEntity dbUser = findUserByUsername(username);
        if (dbUser == null || StringUtils.isEmpty(dbUser.getNickname())) {
            throw new UserException(401, "用户名不存在！");
        }
        if (encoder.matches(password, dbUser.getPassword())) {
            var target = new LoginUser();
            BeanUtils.copyProperties(dbUser, target);
            return target;
        }
        throw new UserException(401, "密码不正确！");
    }

    @Override
    public Set<UserEntity> findFriendList(Integer myId) {
        return baseMapper.findFriendList(myId);

    }

    @Override
    public void addFriend(Integer myid, String friendName) {
        UserEntity friend = findUserByUsername(friendName);
        if (friend != null && friend.getUid() > 0) {
            boolean mark = false;
            for (UserEntity myFriend : findFriendList(myid)) {
                // 如果有这个朋友，那么将 mark 设置为 true，
                if (myFriend.getUid().equals(friend.getUid()) &&
                        myFriend.getUsername().equals(friend.getUsername())) {
                    mark = true;
                }
            }
            if (!mark) {
                UserEntity myUser = findById(myid);
                try {
                    easemobImService.addFriend(myUser.getUsername(), friend.getUsername());
                    Integer save1 = friendService.save(
                            new FriendEntity(null, myUser.getUid(), friend.getUid(), LocalDateTime.now())
                    );
                    Integer save2 = friendService.save(
                            new FriendEntity(null, friend.getUid(), myUser.getUid(), LocalDateTime.now())
                    );
                    log.info("添加好友： {}  {}", save1, save2);
                } catch (UserException e) {
                    log.error("[异常] 添加好友: {}", e.getMessage());
                }
            }
        }
    }

}
